package chpt09;

public class UnSynchronizedThreadTest {
	public static void main(String[] args) throws InterruptedException {
		int n = 1000; // 执行次数
		Counter c = new Counter();
		Thread t1 = new Thread(new IncrementTask(n, c));
		Thread t2 = new Thread(new IncrementTask(n, c));
		Thread t3 = new Thread(new IncrementTask(n, c));
		Thread t4 = new Thread(new DecrementTask(n, c));
		Thread t5 = new Thread(new DecrementTask(n, c));
		Thread t6 = new Thread(new DecrementTask(n, c));

		t1.start();t2.start();t3.start();t4.start();t5.start();t6.start();
		t1.join();t2.join();t3.join();t4.join();t5.join();t6.join();
		System.out.println("counter's value="+c.getValue());
		System.out.println("main end");
	}
}

class Counter { // 计数器
	private int value = 0;
	
	public void inc() { // public synchronized void inc(){
		value++;
	}
	public void dec() {
        value--;
		/*synchronized (this) {
			value--;
		}*/	
	}
	public int getValue() {
		return value;
	}
}

class IncrementTask implements Runnable {
	private int n; // 执行次数
	private Counter c;
	public IncrementTask(int n, Counter c) {
		this.n = n;
		this.c = c;
	}
	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			c.inc();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}

class DecrementTask implements Runnable {
	private int n;
	private Counter c;
	public DecrementTask(int n, Counter c) {
		this.n = n;
		this.c = c;
	}
	@Override
	public void run() {
		for (int i = 0; i < n; i++)
			c.dec();
		String name = Thread.currentThread().getName();
		System.out.println(name + " end");
	}
}
